#include "Drv_DAC8552.h"


#define USE_BITBAND (0)
#if USE_BITBAND
  #include "bitband.h"

#else
  #define scl(x)    HAL_GPIO_WritePin(DAC8552_SCL_GPIO_Port,  DAC8552_SCL_Pin,  (x) ?GPIO_PIN_SET :GPIO_PIN_RESET)
  #define mosi(x)   HAL_GPIO_WritePin(DAC8552_MOSI_GPIO_Port, DAC8552_MOSI_Pin, (x) ?GPIO_PIN_SET :GPIO_PIN_RESET)
  #define sync(x)   HAL_GPIO_WritePin(DAC8552_SYNC_GPIO_Port, DAC8552_SYNC_Pin, (x) ?GPIO_PIN_SET :GPIO_PIN_RESET)
#endif


void sendByte(uint8_t byte)
{
  uint32_t i;

  for(i = 0; i < 8; ++i)
  {
    mosi( (byte & 0x80) );
    byte <<= 1;
    scl(1);
    scl(0);
  }
}

void DAC8552_Init()
{
  sync(1);
  HAL_Delay(10);
}

/*
  输出调理简介
  Vout of DAC8552:  0 ~ Vref(2.5V)
  first stage:      -2.5 ~ 2.5
  second stage:     -5 ~ 5
*/
void DAC8552_setChanValue(uint32_t ch_AorB, uint16_t chValue)
{
  uint8_t  header = 0;
  uint8_t  Hbyte = 0, Lbyte = 0;

  // header_A: 0x10, header_B: 0x24
  header  = (ch_AorB) ?0x24 :0x10;
  Hbyte   = (uint8_t)(chValue >> 8);
  Lbyte   = (uint8_t)(chValue);

  sync(0);
  sendByte(header);
  sendByte(Hbyte);
  sendByte(Lbyte);
  sync(1);

  HAL_Delay(5);
}


uint16_t DAC8552_conv(int32_t Vout_mv)
{
  return (uint16_t)((Vout_mv+5000)*65535/10000);
}
